package atguigu.gulimall.seckill.service.impl;

import atguigu.gulimall.seckill.feign.CouponFeignService;
import atguigu.gulimall.seckill.feign.ProductFeignService;
import atguigu.gulimall.seckill.interceptor.LoginUserInterceptor;
import atguigu.gulimall.seckill.service.SeckillService;
import atguigu.gulimall.seckill.to.SeckillSkuRedisTo;
import atguigu.gulimall.seckill.vo.SeckillSessionsWithSkus;
import atguigu.gulimall.seckill.vo.SkuInfoVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.mq.SeckillOrdetInfoTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import jodd.datetime.TimeUtil;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUINFO_CACHE_PREFIX = "seckill:skus:";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";

    @Override
    public void uploadSeckillLast3DaysProduct() {
        //1.扫描最近3天需要参与秒杀的活动
        //上架商品
        R r = couponFeignService.getSeckillLast3DaysSessions();
        List<SeckillSessionsWithSkus> sessionsWithSkuses = r.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
        });
        if (r.getCode() == 0 && sessionsWithSkuses != null && sessionsWithSkuses.size() > 0) {
            //缓存到redis
            //1、缓存活动信息
            saveSessionInfos(sessionsWithSkuses);
            //2、缓存活动的关联商品信息
            saveSessionSkuInfos(sessionsWithSkuses);
            System.out.println("上架商品完毕........");
        }
    }

    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //1.获取当前活动的时间段,是否在活动的时间段里
        long now = new Date().getTime();
        //2.获取存储在redis中的活动时间段
        Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        for (String key : keys) {
            String redisTime = key.replace(SESSIONS_CACHE_PREFIX, "");
            String[] allTime = redisTime.split("_");
            long startTime = Long.parseLong(allTime[0]);
            long endTime = Long.parseLong(allTime[1]);
            //判断当前时间是否在秒杀的时间段内
            if (now >= startTime && now <= endTime) {
                //获取当前时间段的商品信息
                BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUINFO_CACHE_PREFIX);
                List<String> skuIds = redisTemplate.opsForList().range(key, 0, -1);
                List<String> skuInfo = ops.multiGet(skuIds);
                if (skuInfo != null) {
                    List<SeckillSkuRedisTo> skuRedisTos = skuInfo.stream().map(item -> {
                        SeckillSkuRedisTo skuRedisTo = JSONObject.parseObject(item, SeckillSkuRedisTo.class);
                        return skuRedisTo;
                    }).collect(Collectors.toList());
                    return skuRedisTos;
                }
            }
        }
        return null;
    }


    private void saveSessionInfos(List<SeckillSessionsWithSkus> sessions) {
        sessions.stream().forEach(session -> {
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();
            String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
            if (!redisTemplate.hasKey(key)) {
                List<String> collect = session.getRelationEntityList().stream().map(sku -> sku.getPromotionSessionId() + "_" + sku.getSkuId().toString())
                        .collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key, collect);
            }
        });
    }

    private void saveSessionSkuInfos(List<SeckillSessionsWithSkus> sessions) {

        sessions.stream().forEach(session -> {
            //装备hash操作
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUINFO_CACHE_PREFIX);

            session.getRelationEntityList().forEach(skuInfoVo -> {
                //缓存商品
                SeckillSkuRedisTo seckillSkuRedisTo = new SeckillSkuRedisTo();
                //1.sku的基本数据
                R r = productFeignService.getSkuInfo(skuInfoVo.getSkuId());
                if (r.getCode() == 0) {
                    SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                    });
                    seckillSkuRedisTo.setSkuInfo(skuInfo);
                }
                //2.sku的秒杀信息
                BeanUtils.copyProperties(skuInfoVo, seckillSkuRedisTo);

                //3.设置商品中活动的开始时间和结束时间
                seckillSkuRedisTo.setStartTime(session.getStartTime().getTime());
                seckillSkuRedisTo.setEndTime(session.getEndTime().getTime());

                //4.设置秒杀商品中的随机码,防止内部人员指导商品的id,确保公平性
                String token = UUID.randomUUID().toString().replaceAll("-", "");
                seckillSkuRedisTo.setRandomCode(token);

                if (!ops.hasKey(skuInfoVo.getPromotionSessionId() + "_" + skuInfoVo.getSkuId().toString())) {
                    //5.使用redis的信号量进行限流
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    semaphore.trySetPermits(skuInfoVo.getSeckillCount().intValue());
                    //将数据存入redis中
                    String seckillSkuInfoJsonString = JSON.toJSONString(seckillSkuRedisTo);
                    ops.put(skuInfoVo.getPromotionSessionId() + "_" + skuInfoVo.getSkuId().toString(), seckillSkuInfoJsonString);
                }
            });
        });
    }

    @Override
    public SeckillSkuRedisTo getSeckillSkuItemInfo(Long skuId) {
        //1、查询所有秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUINFO_CACHE_PREFIX);
        String regx = "\\d_" + skuId;
        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0) {
            for (String key : keys) {
                if (Pattern.matches(regx, key)) {
                    String skuInfo = hashOps.get(key);
                    SeckillSkuRedisTo redisTo = JSONObject.parseObject(skuInfo, SeckillSkuRedisTo.class);
                    long nowTime = new Date().getTime();
                    if (nowTime >=redisTo.getStartTime() && nowTime<=redisTo.getEndTime()){}
                    else {
                        redisTo.setRandomCode(null);
                    }
                    return redisTo;
                }
            }
        }
        return null;
    }

    @Override
    public String createSeckillOrderSn(String killId, String key, Integer num) {
        MemberResponseVo memberResponseVo = LoginUserInterceptor.loginUser.get();

        //1、验证当前时间是否在秒杀的时间内
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUINFO_CACHE_PREFIX);
        String redisSkuInfoString = hashOps.get(killId);
        if(!StringUtils.isEmpty(redisSkuInfoString)){
            SeckillSkuRedisTo seckillSkuRedisTo = JSONObject.parseObject(redisSkuInfoString, SeckillSkuRedisTo.class);
            long nowTime = new Date().getTime();
            long liveTime = seckillSkuRedisTo.getEndTime()-nowTime;
            String skuInfoId=seckillSkuRedisTo.getPromotionSessionId()+"_"+seckillSkuRedisTo.getSkuId();
            if (nowTime>=seckillSkuRedisTo.getStartTime() && nowTime<=seckillSkuRedisTo.getEndTime()){
                //2.判断当前随机码与页面的随机码是否相同
                if (seckillSkuRedisTo.getRandomCode().equals(key) && killId.equals(skuInfoId)){
                    //3、验证购物数量是否合理,根据业务要求看是否一个人只能秒杀一件还是任意件
                    if(num<=seckillSkuRedisTo.getSeckillCount().intValue()){
                        //4.验证这个人是否有已经买过,防止一个人重复购买,进行幂等性处理
                        //设置设置redis的key占坑,键为用户Id+场次Id+产品Id
                        String userInfoKey=memberResponseVo.getId()+"_"+skuInfoId;
                        //进行redis占位
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(userInfoKey, num.toString(),liveTime, TimeUnit.MILLISECONDS);
                        if(aBoolean){
                            //进行信号量的扣减操作
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + seckillSkuRedisTo.getRandomCode());
                            try {
                                boolean tryAcquire = semaphore.tryAcquire(num);
                                if(tryAcquire){
                                    //快速下单
                                    //秒杀成功了,生成订单号
                                    //发送消息去MQ
                                    String orderSn = IdWorker.getTimeId();
                                    //封装发给MQ的数据模型
                                    SeckillOrdetInfoTo seckillOrdetInfoTo = new SeckillOrdetInfoTo();
                                    seckillOrdetInfoTo.setOrderSn(orderSn);
                                    seckillOrdetInfoTo.setMemberId(memberResponseVo.getId());
                                    seckillOrdetInfoTo.setSeckillPrice(seckillSkuRedisTo.getSeckillPrice());
                                    seckillOrdetInfoTo.setSkuId(seckillSkuRedisTo.getSkuId());
                                    seckillOrdetInfoTo.setPromotionSessionId(seckillSkuRedisTo.getPromotionSessionId());
                                    seckillOrdetInfoTo.setNum(num);
                                    //MQ发送消息
                                    rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",seckillOrdetInfoTo);
                                    return orderSn;
                                }
                            } catch (Exception e) {
                                return null;
                            }

                        }
                    }
                }
            }
        }
        return null;
    }
}
